package com.tanhua.dubbo.server.api;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.common.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.pojo.Users;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.util.concurrent.TimeUnit;

@Service
public class SoundTransmissionApiImpl implements SoundTransmissionApi {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;//格式要改为String

    @Autowired
    private MongoTemplate mongoTemplate;

    @Reference
    private UserLikeApi userLikeApi;


    private static final String REMAININGTIMES_REDIS_KEY_PREFIX = "REMAININGTIMES_COMMENT_";

    //查找好友
    //用户不喜欢的key前缀
    public static final String NOT_LIKE_REDIS_KEY_PREFIX = "USER_NOT_LIKE_";

    //发送语音
    @Override
    public Boolean soundSound(Long id, String soundUrl) {
        //创建探花传音表b并添加数据
        Sound sound = new Sound();
        sound.setId(new ObjectId());
        sound.setUserId(id);
        sound.setCreated(System.currentTimeMillis());
        sound.setStrUrl(soundUrl);
        Sound save = this.mongoTemplate.save(sound);

        //判断是否保存到MongoDB数据库中
        if (ObjectUtil.isNotEmpty(save)) {
            return true;
        }

        return false;
    }

    //计算当日接收的次数
    @Override
    public Integer remainingTimes(Long id) {
        //拿到key和value
        String redisKey = this.redisCount(id);
        String count = this.redisTemplate.opsForValue().get(redisKey);
        //拿到当前的时间
        String newDate = DateUtil.format(new Date(), "yyyy-MM-dd");
        //拿到之前存的时间
        String oldDay = this.redisTemplate.opsForValue().get("oldDay" + id);
        //判断是否是新的一天
        if (!newDate.equalsIgnoreCase(oldDay)) {
            //新的一天就删除之前在redis中的缓存
            this.redisTemplate.delete("oldDay" + id);
            this.redisTemplate.delete(redisKey);
        }

        //如果不为空就返回数据
        if (ObjectUtil.isNotEmpty(count) && Convert.toInt(count) >= 0) {
            //让其每次自减一次
            this.redisTemplate.opsForValue().increment(redisKey, -1);
            //查询次数并返回
            String number = this.redisTemplate.opsForValue().get(redisKey);
            return Convert.toInt(number);
        } else {
            //如果次数没有或者redis中的数据还有就返回null
            if (ObjectUtil.isNotEmpty(count) && Convert.toInt(count) < 0) {
                return null;
            } else {
                //如果为空就新建一个存在redis数据库中
                this.redisTemplate.opsForValue().set(redisKey, "10", 1, TimeUnit.DAYS);
                //设置添加时间
                this.redisTemplate.opsForValue().set("oldDay" + id, DateUtil.format(new Date(), "yyyy-MM-dd"), 1, TimeUnit.DAYS);
                //因为用户已经点了一次,所以只需要返回9次就行了
                String firstCount = this.redisTemplate.opsForValue().get(redisKey);
                return Convert.toInt(firstCount);
            }
        }

    }

    //查询排名缘分值靠前的十个人并且这个人是不在喜欢表和不喜欢表的
    @Override
    public List<RecommendUser> queryRecommendList(Long id) {


        //查找好友ID
        Query query = Query.query(Criteria.where("userId").is(id));
        List<Users> usersList = this.mongoTemplate.find(query, Users.class);
        //拿到所有人的ID
        List<Object> friendIdList = CollUtil.getFieldValues(usersList, "friendId");
        List<Long> userIdList = new ArrayList<>();
        //转换格式
        for (Object userId : friendIdList) {
            userIdList.add(Convert.toLong(userId));
        }

        //通过id在缘分表查找所有的人
        Query query2 = Query.query(Criteria.where("toUserId").is(id).and("userId").nin(userIdList));
        List<RecommendUser> recommendUserList = this.mongoTemplate.find(query2, RecommendUser.class);


        //判断是否有在喜欢表
        for (RecommendUser recommendUser : recommendUserList) {
            //查看是否是不喜欢的
            String redisKey = NOT_LIKE_REDIS_KEY_PREFIX + id;
            String hashKey = String.valueOf(recommendUser.getUserId());
            Object unLike = this.redisTemplate.opsForHash().get(redisKey, hashKey);
            //如果不是喜欢和不喜欢的那就可以返回
            if (ObjectUtil.isEmpty(unLike)) {
                return recommendUserList;
            }
        }
        return null;
    }


    //查找语音
    @Override
    public Sound acceptSound(Long userId) {
        //查找语音并且按照发布的时间进行选择
        PageRequest pageRequest = PageRequest.of(0, 1, Sort.by(Sort.Order.desc("created")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        Sound sound = this.mongoTemplate.findOne(query, Sound.class);
        //非空校验
        if (ObjectUtil.isNotEmpty(sound)) {
            return sound;
        }
        return null;
    }

    //获取rediskey的方法
    public String redisCount(Long id) {
        return this.REMAININGTIMES_REDIS_KEY_PREFIX + id;
    }
}
